package client;

import javax.swing.JFrame;

import com.jpemartin.jgt.HasKeyboard;
import com.jpemartin.jgt.HasSize;
import com.jpemartin.jgt.KeyboardStatus;

public abstract class BaseFrame extends JFrame implements Runnable,
		HasKeyboard, HasSize {

	private static final long serialVersionUID = 5242652889556100597L;

	/** window title **/
	protected String _name;
	/** main game thread **/
	protected Thread _mythread;
	/** always true for now **/
	protected boolean _directDraw = true;
	/** keeps track of keypresses **/
	protected KeyboardStatus _kb;

	/**
	 * set to true initially, and to false when the user clicks the "close"
	 * button. You should then release resources and let the run() method return
	 * so we can quit gracefully.
	 */
	public boolean _gameRunning;

	// --- methods you must override ---

	// (this being abstract prevents programmers from never learning how to set
	// a title for their app)

	/**
	 * You must write this function, return a string that describes the game. It
	 * will be shown in the title bar when the game is ran as an application
	 * rather than an applet.
	 */
	public abstract String getName();

	// (having these methods as abstract makes sure the user code won't compile
	// if he doesn't override
	// them, preventing weirdness such as a 0-width game window).

	/** You must rewrite this function to return the height of the game window **/
	public abstract int getHeight();

	/** You must rewrite this function to return the width of the game window **/
	public abstract int getWidth();

	/**
	 * Call this function every time you're done drawing one frame. It will show
	 * the picture and wait a little bit.
	 */
	public void showAndWait() {

		// Min priority, let applet thread draw the picture
		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

		try {
			// sleep between every frame
			Thread.sleep(20);
			
		} catch (InterruptedException ex) {
			// that one frame will go faster, no big deal
		}

		// Max priority now, we must compute the next frame
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
	}

	/** called when the applet starts. Creates a thread for the game. **/
	public void start() {

		_kb = new KeyboardStatus();
		addKeyListener(_kb);

		synchronized (this) {
			// make sure nothing bad happens if this is called twice
			// (can't trust the browser to only call us once)
			if (_gameRunning)
				return;

			_gameRunning = true;
			// start a new thread to run the game on
			_mythread = new Thread(this);
			_mythread.start();

		}

	}

	@Override
	public KeyboardStatus getKeyboardStatus() {
		return _kb;
	}

	@Override
	public void run() {

	}

}
